import { useState, useEffect } from 'react';
import { Button, Modal, Form, Input, InputNumber } from 'antd';
import { useStore } from '@/store';
import { nanoid } from 'nanoid';

const ImageModal = ({ visibleImageModal, isAdd, elementsIndex }) => {
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();
  const { slideList, currentSlideIndex, setCurrentPresentation, updateSlide } = useStore();

  useEffect(() => {
    if (visibleImageModal) {
      setModalVisible(true);

      if (isAdd) {
        form.resetFields();
      } else {
        // 编辑进来
        const { blockWidth, blockHeight, describe, imageUrl } =
          slideList[currentSlideIndex - 1].elements[elementsIndex];
        form.setFieldsValue({
          blockWidth,
          blockHeight,
          describe,
          imageUrl,
        });
      }
    }
  }, [visibleImageModal]);

  const handleCancel = () => {
    form.resetFields();
    setModalVisible(false);
  };

  const handleOK = () => {
    form.validateFields().then((values) => {
      const newSlideList = [...slideList];
      if (isAdd) {
        // 新增一个元素
        newSlideList[currentSlideIndex - 1].elements.push({
          sortId: newSlideList[currentSlideIndex - 1].elements.length + 1, // 排序id
          id: nanoid(),
          type: 'Image',
          ...values,
        });
      } else {
        // 修改一个元素
        newSlideList[currentSlideIndex - 1].elements[elementsIndex] = {
          ...newSlideList[currentSlideIndex - 1].elements[elementsIndex],
          ...values,
        };
      }
      //  修改一个元素时
      updateSlide(newSlideList);
      setModalVisible(false);
    });
  };

  return (
    <Modal title={'设置图片'} open={modalVisible} onCancel={handleCancel} onOk={handleOK}>
      <Form
        labelCol={{ span: 6 }}
        form={form}
        initialValues={{
          blockWidth: 500,
          blockHeight: 250,
          imageUrl: '',
          describe: '',
        }}
      >
        <Form.Item
          label="图片宽度"
          name="blockWidth"
          rules={[{ required: true, message: '不得为空' }]}
        >
          <InputNumber style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item
          label="图片高度"
          name="blockHeight"
          rules={[{ required: true, message: '不得为空' }]}
        >
          <InputNumber style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item
          label="图片地址"
          name="imageUrl"
          rules={[{ required: true, message: '不得为空' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item label="图片描述" name="describe">
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default ImageModal;
